using Hotran.Audio;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

namespace Roots.UI
{
    public class UiHandler : MonoBehaviour
    {
        [SerializeField] Game game;

        [Header("Scores")]
        [SerializeField] Text[] resourceTexts;
        [SerializeField] Text scoreText;
        [SerializeField] Text starText;

        [Header("Help")]
        [SerializeField] Dialog tipDialog;
        [SerializeField] Button helpButton;
        [SerializeField] Button closeTipButton;
        [SerializeField] BubbleUi helpBubble;

        [Header("Menu")]    
        [SerializeField] RectTransform menuDialog;
        [SerializeField] Button menuButton;
        [SerializeField] Button resumeButton;
        [SerializeField] Button quitButton;
        [SerializeField] Button[] restartButtons;

        [Header("Win")]
        [SerializeField] Dialog winDialog;
        [SerializeField] Text winText;
        [SerializeField] AudioClip winSound;

        public event UnityAction GameOver;

        /// <summary>
        /// UI是否处于打开状态
        /// </summary>
        public bool IsUiOpen => tipDialog.IsOpen ||
            menuDialog.gameObject.activeSelf ||
            winDialog.IsOpen;


        // Start is called before the first frame update
        void Start()
        {
            menuDialog.gameObject.SetActive(false);
            helpButton.onClick.AddListener(ToggleTip);
            closeTipButton.onClick.AddListener(ToggleTip);
            menuButton.onClick.AddListener(ToggleMenu);
            resumeButton.onClick.AddListener(ToggleMenu);
            quitButton.onClick.AddListener(game.Quit);
            foreach (var button in restartButtons)
                button.onClick.AddListener(game.Restart);
        }

        public void UpdateResScores(int[] resources, int score)
        {
            resourceTexts[0].text = resources[0].ToString();
            resourceTexts[1].text = resources[1].ToString();
            scoreText.text = score.ToString();
        }

        public void UpdateStar(int stars)
        {
            starText.text = stars.ToString();
        }

        public void ShowGameOver(int score)
        {
            AudioPlayer.Instance.PlaySound(winSound);
            GameOver?.Invoke();
            Debug.Log($"游戏结束！您的分数为{score}");
            winText.text = score.ToString();
            winDialog.Toggle();
            game.GameOver();
        }

        public void ToggleTip()
        {
            if (Time.timeScale == 0f) return;
            Game.TipShowed = true;
            tipDialog.Toggle();

            if (helpBubble.IsOpen)
                helpBubble.Hide();
        }

        public void ToggleMenu()
        {
            menuDialog.gameObject.SetActive(!menuDialog.gameObject.activeSelf);
            game.TogglePause();
        }

        public void ShowHelpBubble()
        {
            helpBubble.Open();
        }
    }
}